package net.tycmc.cty.ctyms.timejob.iems.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.tycmc.functions.util.NumberFormat;
import com.tycmc.functions.util.StringUtil;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.cty.ctyms.timejob.common.ExceptionDataProcess;
import net.tycmc.cty.ctyms.timejob.common.ListUtil;
import net.tycmc.cty.ctyms.timejob.common.UnifideCaculation;
import net.tycmc.cty.ctyms.timejob.iems.dao.DrivingBehaviorScoreDAO;

public class DrivingBehaviorScoreService {
	
	private  DrivingBehaviorScoreDAO dbsd;
	public DrivingBehaviorScoreDAO getDbsd() {
		return dbsd;
	}
	public void setDbsd(DrivingBehaviorScoreDAO dbsd) {
		this.dbsd = dbsd;
	}
	/**
	 * 驾驶行为评分开始
	 * 此Job的执行需要在档位车速统计执行完之后   
	 **/
	public void startWork() {
		Date date1 = new Date();
		//统计日期
		String workDate=DateUtil.addDay(-1);
		System.out.println("驾驶行为评分开始："+date1.toString());
		//获取发动机类型及规则
		List<Map<String,Object>>listRule=dbsd.getTheEngRule();
		Map<String,List<Map<String,Object>>>mapRule=new ListUtil().groupBy("DBSR_EgnType",listRule);
		//获取设备基本信息及行为I
		List<Map<String,Object>>listDrHavior1=dbsd.getVclInfo(workDate);
		//存储sql
		List<String>listSql=new ArrayList<String>();
		//驾驶行为II
		Map<String,Map<String,Object>>mapdb2=dbsd.Db2Operate(workDate);
		int sussNum=0;
		if(null!=listDrHavior1&&listDrHavior1.size()>0){
			for(Map<String,Object>mapVcl:listDrHavior1){
				String vclId=MapGetter.getString(mapVcl,"MsgESS_Vcl_ID");
				String EngineModel=MapGetter.getString(mapVcl,"EngineModel");
				//获取此发动机的评分规则
				List<Map<String,Object>>listTheEgnRule=mapRule.get(EngineModel);
				//若发动机不存在评分规则
				if(null==listTheEgnRule||listTheEgnRule.size()==0){
					continue;
				}else{
					this.getPerVclScore(listTheEgnRule,mapdb2.get(vclId),mapVcl,vclId,EngineModel,listSql,workDate);
					sussNum++;
				}
			}
			boolean flag=dbsd.execBatch(listSql);
			if(flag==true){
				System.out.println("---------执行成功,本次成功插入"+sussNum+"台车的数据----------------");
			}else{
				System.out.println("---------执行失败,本次未插入"+sussNum+"台车的数据-----------------");
			}
		}
		System.out.println("驾驶行为评分结束："+new Date().toString()+",用时："+(new Date().getTime()-date1.getTime())/(1000)+"秒");
	}
	/**获取驾驶行为评分
	 * @param listTheEgnRule   此台车规则
	 * @param mapDb2		   此台车驾驶行为2
	 * @param mapDs1		此台车驾驶行为1
	 * @return
	 */
	public List<String> getPerVclScore(List<Map<String,Object>>listTheEgnRule,Map<String,Object>mapDb2,Map<String,Object>mapDs1,String vclId,String EngineModel,List<String>listSql,String workDate){
		String startMonth=workDate.substring(0, 7).replace("-", "");
		List<String>listDsBehavior=new ArrayList<String>();
		//油耗
		String toRunOil=ExceptionDataProcess.RunOil(MapGetter.getString(mapDs1,"toRunOil"),DateUtil.addDay(-1),DateUtil.addDay(-1),1,2);
		//里程
		String toRunKm=ExceptionDataProcess.RunOil(MapGetter.getString(mapDs1,"toRunKm"),DateUtil.addDay(-1),DateUtil.addDay(-1),1,2);
		if("--".equals(toRunKm)){
			toRunKm="0";
		}
		//工作时长
		String toRunTime=ExceptionDataProcess.RunOil(MapGetter.getString(mapDs1,"toRunTime"),DateUtil.addDay(-1),DateUtil.addDay(-1),1,2);
		if("--".equals(toRunTime)){
			toRunTime="0";
		}
		if(null==mapDb2||mapDb2.size()==0){
			mapDb2=new HashMap<String, Object>();
		}
		/**-------------------------------------------------------------经济评分---------------------------------------------------------------*/
		
		//(吨/每百公里)即平均载重
		String avgLoad=StringUtil.isValid(MapGetter.getString(mapDs1,"avgLoad"))?MapGetter.getString(mapDs1,"avgLoad"):"0";
		//刹车次数
		String SCTimes=StringUtil.isValid(MapGetter.getString(mapDs1,"SCTimes"))?MapGetter.getString(mapDs1,"SCTimes"):"0";
		//经济评分-急加速次数
		String JJSTimes=StringUtil.isValid(MapGetter.getString(mapDs1,"JJSTimes"))?MapGetter.getString(mapDs1,"JJSTimes"):"0";
		//全油门里程
		String QYMKm=StringUtil.isValid(MapGetter.getString(mapDs1,"QYMKm"))?MapGetter.getString(mapDs1,"QYMKm"):"0";
		//空挡踩油门次数
		String KDCYMTimes=StringUtil.isValid(MapGetter.getString(mapDs1,"KDCYMTimes"))?MapGetter.getString(mapDs1,"KDCYMTimes"):"0";
		//经济区时间占比(驾驶行为2）
		String JJQTime=StringUtil.isValid(MapGetter.getString(mapDb2,"ecoArea"))?MapGetter.getString(mapDb2,"ecoArea"):"0";
		//超转速时间占比
		String CZSTime=StringUtil.isValid(MapGetter.getString(mapDs1,"CZSTime"))?MapGetter.getString(mapDs1,"CZSTime"):"0";
		//超速行驶时间占比
		String CSXSTime=StringUtil.isValid(MapGetter.getString(mapDs1,"CSXSTime"))?MapGetter.getString(mapDs1,"CSXSTime"):"0";
		//超长怠速时长
		String longIdleTime=StringUtil.isValid(MapGetter.getString(mapDs1,"longIdleTime"))?MapGetter.getString(mapDs1,"longIdleTime"):"0";
		//低档高速时长(驾驶行为2）
		String lowHighTime=StringUtil.isValid(MapGetter.getString(mapDb2,"loHiArea"))?MapGetter.getString(mapDb2,"loHiArea"):"0";
		
		/**------------------------------------------------------安全评分----------------------------------------------------------*/
		
		//急刹车次数
		String JSCTimes=StringUtil.isValid(MapGetter.getString(mapDs1,"JSCTimes"))?MapGetter.getString(mapDs1,"JSCTimes"):"0";
		//安全评分-急加速次数
		String JJSTimes_2=StringUtil.isValid(MapGetter.getString(mapDs1,"JJSTimes_2"))?MapGetter.getString(mapDs1,"JJSTimes_2"):"0";
		//疲劳驾驶时长占比
		String PLJSTime=StringUtil.isValid(MapGetter.getString(mapDs1,"PLJSTime"))?MapGetter.getString(mapDs1,"PLJSTime"):"0";
		//超速行驶时间占比
		String CSXSTime_2=StringUtil.isValid(MapGetter.getString(mapDs1,"CSXSTime_2"))?MapGetter.getString(mapDs1,"CSXSTime_2"):"0";
		//高速空挡滑行值取字段空挡滑行时长
		String KDHXTime=StringUtil.isValid(MapGetter.getString(mapDs1,"KDHXTime"))?MapGetter.getString(mapDs1,"KDHXTime"):"0";
		
		/**-------------------------------------------------------寿命评分-----------------------------------------------------*/
		
		//高档低速时间占比(驾驶行为2）
		String GDDSTime=StringUtil.isValid(MapGetter.getString(mapDb2,"hiLoArea"))?MapGetter.getString(mapDb2,"hiLoArea"):"0";
		//高速空挡滑行值取字段空挡滑行时长
		String KDHXTime_2=StringUtil.isValid(MapGetter.getString(mapDs1,"KDHXTime"))?MapGetter.getString(mapDs1,"KDHXTime"):"0";
		
		/**--------------------------------------------------------百分比-------------------------------------------------------------*/
		
		/**---------------------------------------------------经济评分---------------------------------------------------------------*/
		//百公里油耗
		String oilPerKm="0";
		//(吨/每百公里)即平均载重
		String avgLoadPersent="0";
		//刹车次数
		String SCTimesPersent="0";
		//经济评分-急加速次数
		String JJSTimesPersent="0";
		//全油门
		String QYMKmPersent="0";
		//空挡踩油门次数
		String KDCYMTimesPersent="0";
		//经济区时间占比(驾驶行为2）
		String JJQTimePersent="0";
		//超转速时间占比
		String CZSTimePersent="0";
		//超速行驶时间占比
		String CSXSTimePersent="0";
		//超长怠速时长
		String longIdleTimePersent="0";
		//低档高速时长(驾驶行为2）
		String lowHighTimePersent="0";
		
		/**----------------------------------------------------------安全评分---------------------------------------------------------*/
		
		//急刹车次数
		String JSCTimesPersent="0";
		//安全评分-急加速次数
		String JJSTimes_2Persent="0";
		//疲劳驾驶时长占比
		String PLJSTimePersent="0";
		//超速行驶时间占比
		String CSXSTime_2Persent="0";
		//高速空挡滑行值取字段空挡滑行时长
		String KDHXTimePersent="0";
		
		/**-----------------------------------------------------------寿命评分-----------------------------------------------------------*/
		
		//高档低速时间占比(驾驶行为2）
		String GDDSTimePersent="0";
		//高速空挡滑行值取字段空挡滑行时长
		String KDHXTime_2Persent="0";
		
		//百公里油耗
		oilPerKm=UnifideCaculation.AverageLKm(toRunKm, toRunOil, 2);
		oilPerKm=StringUtil.isValid(oilPerKm)&&!"--".equals(oilPerKm)?oilPerKm:"0";
		//数据异常--和null都按0处理
		if(0!=Double.parseDouble(toRunKm)){
			//avgLoadPersent=String.valueOf(NumberFormat.div(Float.parseFloat(avgLoad)*100, Float.parseFloat(toRunKm), 2));
			avgLoadPersent=String.valueOf(NumberFormat.div(Float.parseFloat(avgLoad),1, 2));
			SCTimesPersent=String.valueOf(NumberFormat.div(Float.parseFloat(SCTimes)*100,Float.parseFloat(toRunKm),2));
			JJSTimesPersent=String.valueOf(NumberFormat.div(Float.parseFloat(JJSTimes)*100,Float.parseFloat(toRunKm),2));
			QYMKmPersent=String.valueOf(NumberFormat.div(Float.parseFloat(QYMKm)*100,Float.parseFloat(toRunKm),2));
			KDCYMTimesPersent=String.valueOf(NumberFormat.div(Float.parseFloat(KDCYMTimes)*100,Float.parseFloat(toRunKm),2));
			JSCTimesPersent=String.valueOf(NumberFormat.div(Float.parseFloat(JSCTimes)*100,Float.parseFloat(toRunKm),2));
			JJSTimes_2Persent=String.valueOf(NumberFormat.div(Float.parseFloat(JJSTimes_2)*100,Float.parseFloat(toRunKm),2));
			PLJSTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(PLJSTime)*100,Float.parseFloat(toRunKm),2));
		}
		if(0!=Double.parseDouble(toRunTime)){
			CZSTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(CZSTime)*100,Float.parseFloat(toRunTime),2));
			CSXSTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(CSXSTime)*100,Float.parseFloat(toRunTime),2));
			longIdleTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(longIdleTime)*100,Float.parseFloat(toRunTime),2));
			CSXSTime_2Persent=String.valueOf(NumberFormat.div(Float.parseFloat(CSXSTime_2)*100,Float.parseFloat(toRunTime),2));
			KDHXTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(KDHXTime)*100,Float.parseFloat(toRunTime),2));
			KDHXTime_2Persent=String.valueOf(NumberFormat.div(Float.parseFloat(KDHXTime_2)*100,Float.parseFloat(toRunTime),2));
		}
		/********************************************驾驶行为II************************************/
		JJQTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(JJQTime),1,2));//经济区时间占比
		lowHighTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(lowHighTime),1,2));//低档高速时间占比
		GDDSTimePersent=String.valueOf(NumberFormat.div(Float.parseFloat(GDDSTime),1,2));//高档低速时间占比
		/********************************************驾驶行为II************************************/
		
		listDsBehavior.add(oilPerKm);
		listDsBehavior.add(avgLoadPersent);
		listDsBehavior.add(SCTimesPersent);
		listDsBehavior.add(JJSTimesPersent);
		listDsBehavior.add(QYMKmPersent);
		listDsBehavior.add(KDCYMTimesPersent);
		listDsBehavior.add(JJQTimePersent);
		listDsBehavior.add(CZSTimePersent);
		listDsBehavior.add(CSXSTimePersent);
		listDsBehavior.add(longIdleTimePersent);
		listDsBehavior.add(lowHighTimePersent);
		listDsBehavior.add(JSCTimesPersent);
		listDsBehavior.add(JJSTimes_2Persent);
		listDsBehavior.add(PLJSTimePersent);
		listDsBehavior.add(CSXSTime_2Persent);
		listDsBehavior.add(KDHXTimePersent);
		listDsBehavior.add(GDDSTimePersent);
		listDsBehavior.add(KDHXTime_2Persent);
		//开始设置分数
		int Type=1;
		for(Map<String,Object>mapresult:listTheEgnRule){
			String DBS_Scorealg="";//分值算法
			double Dbvalue=Double.parseDouble(listDsBehavior.get(Type-1));
			//基础分
			double DBSR_BaScore=Float.parseFloat(MapGetter.getString(mapresult,"DBSR_BaScore"));
			int beKind=0;
			//判断所属行为类型
			if(Type<12){
				beKind=1;
			}else if(Type<17){
				beKind=2;
			}else{
				beKind=3;
			}
			//如果基础分我i-1,则此项不需要展示，也不需要计算
			if(-1==DBSR_BaScore){
				listSql.add("insert into DriverBehaviorScore_"+startMonth+" (DBS_VclID,DBS_EgnType,DBS_BeKind,DBS_BeEvent,DBS_BaScore,DBS_BaRunKm,DBS_BaRunTime,DBS_BaMsgTime,DBS_Content,DBS_jichuScore,DBS_Scorealg) " +
																			"values("+vclId+",'"+EngineModel+"',"+beKind+","+Type+",-1,"+toRunKm+","+toRunTime+",'"+workDate+"',"+Dbvalue+","+DBSR_BaScore+",'"+DBS_Scorealg+"')"); 
				Type++;
				continue;
			}
			//标准分数
			double DBSR_StaValue=Double.parseDouble(MapGetter.getString(mapresult,"DBSR_StaValue"));
			//变化量
			double DBSR_ChaValue=Double.parseDouble(MapGetter.getString(mapresult,"DBSR_ChaValue"));
			//变化分值
			double DBSR_ChaScore=Double.parseDouble(MapGetter.getString(mapresult,"DBSR_ChaScore"));
			Map<String,Object>  unit = Unit(Type);//@_@：基础分DBSR_BaScore  &_&：标准分DBSR_StaValue  #_#：变化量DBSR_ChaValue   -_-：变化分值DBSR_ChaScore
			DBS_Scorealg = MapGetter.getString(unit, "Scorealg")
					.replaceAll("@_@",MapGetter.getString(mapresult,"DBSR_BaScore"))
					.replaceAll("&_&", MapGetter.getString(mapresult,"DBSR_StaValue"))
					.replaceAll("#_#", MapGetter.getString(mapresult,"DBSR_ChaValue"))
					.replaceAll("-_-", MapGetter.getString(mapresult,"DBSR_ChaScore"));
			//最终分数
			double Score=0;
			if(Type==1){//高于标准，每高“变化量”，扣变化分值，低于标准，每低“变化量”，加变化分值。
				if(Dbvalue<=DBSR_StaValue){//加分
					Score=(DBSR_StaValue-Dbvalue)*DBSR_ChaScore/DBSR_ChaValue;
					Score=DBSR_BaScore+NumberFormat.div(Score, 1,2);
				}else{//减分
					Score=(Dbvalue-DBSR_StaValue)*DBSR_ChaScore/DBSR_ChaValue;
					Score=NumberFormat.div(Score, 1,2);
					if(Score>DBSR_BaScore){
						Score=0;
					}else{
						Score=DBSR_BaScore-Score;
					}
				}
			}else if(Type==2){//高于标准，每高“变化量”，加变化分值;低于标准不减分
				if(Dbvalue>DBSR_StaValue){
					Score=(Dbvalue-DBSR_StaValue)*DBSR_ChaScore/DBSR_ChaValue;
					Score=DBSR_BaScore+NumberFormat.div(Score, 1,2);
				}else{
					Score=DBSR_BaScore;
				}
			}else{//高于标准，每高”变化量”，扣“变化分值”；低于标准，不会加分。
				if(Dbvalue>DBSR_StaValue){
					Score=(Dbvalue-DBSR_StaValue)*DBSR_ChaScore/DBSR_ChaValue;
					if(Score>DBSR_BaScore){
						Score=0;
					}else{
						Score=DBSR_BaScore-Score;
					}
				}else{
					Score=DBSR_BaScore;
				}
			}
			listSql.add("insert into DriverBehaviorScore_"+startMonth+" (DBS_VclID,DBS_EgnType,DBS_BeKind,DBS_BeEvent,DBS_BaScore,DBS_BaRunKm,DBS_BaRunTime,DBS_BaMsgTime,DBS_Content,DBS_jichuScore,DBS_Scorealg) " +
															"values("+vclId+",'"+EngineModel+"',"+beKind+","+Type+","+Score+","+toRunKm+","+toRunTime+",'"+workDate+"',"+Dbvalue+","+DBSR_BaScore+",'"+DBS_Scorealg+"')");
			//每个扣分项目，最多扣到0分，不可扣出负分
			Type++;
		}
		return listSql;
	}
	/**
	 * 判断数据值得单位
	 * @_@：基础分DBSR_BaScore  &_&：标准分DBSR_StaValue  #_#：变化量DBSR_ChaValue   -_-：变化分值DBSR_ChaScore
	 * @param i
	 * @return
	 */
	public static Map<String,Object> Unit(int i){
		Map<String,Object> unit=new HashMap<String,Object>();
		if(i==1){
			unit.put("Content", "L/100Km");
			unit.put("Scorealg", "基础@_@分,低于&_&升,每#_#升加-_-分;高于&_&升,每#_#升减-_-分");
		}else if(i==2){
			unit.put("Content", "T");
			unit.put("Scorealg", "基础@_@分,低于&_&吨,每#_#吨加-_-分");
		}else if(i==3||i==4){
			unit.put("Content", "次");
			unit.put("Scorealg", "基础@_@分,高于&_&次,每#_#次减-_-分");
		}else if(i==5){
			unit.put("Content", "Km/100Km");
			unit.put("Scorealg", "基础@_@分,高于&_&公里,每#_#公里减-_-分");
		}else if(i==6||i==12||i==13){
			unit.put("Content", "次/100Km");
			unit.put("Scorealg", "基础@_@分,高于&_&次,每#_#次减-_-分");
		}else if(i==7||i==8||i==9||i==10||i==11||i==15||i==16||i==17||i==18){
			unit.put("Content", "%");
			unit.put("Scorealg", "基础@_@分,高于&_&%,每#_#%,减-_-分");
		}else if(i==14){
			unit.put("Content", "分钟/100Km");
			unit.put("Scorealg", "基础@_@分,高于&_&分组,每#_#分组减-_-分");
		}
		return unit;
	}
	public static void main(String[] args) {
		Map<String,Object>  unit = Unit(1);
		String DBS_Scorealg = MapGetter.getString(unit, "Scorealg").replaceAll("@_@","20")
				.replaceAll("&_&", "10")
				.replaceAll("#_#", "1")
				.replaceAll("@@@", "0.66");
		System.out.println(DBS_Scorealg);
	}
}
